# !pip install -q --upgrade transformers==4.25.1 diffusers ftfy accelerate
Stable Diffusion Deep Dive
Stable Diffusion is a powerful text-to-image model. There are various websites and tools to make using it as easy as possible. It is also integrated into the Huggingface diffusers library where generating images can be as simple as:
from diffusers import StableDiffusionPipeline
= StableDiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v1-4", revision="fp16", torch_dtype=torch.float16, use_auth_token=True).to("cuda")
pipe = pipe("An astronaught scuba diving").images[0] image
In this notebook we’re going to dig into the code behind these easy-to-use interfaces, to see what is going on under the hood. We’ll begin by re-creating the functionality above as a scary chunk of code, and then one by one we’ll inspect the different components and figure out what they do. By the end of this notebook that same sampling loop should feel like something you can tweak and modify as you like.
Setup & Imports
You’ll need to log into huggingface and accept the terms of the licence for this model - see the model card for details. And when you first run this notebook you need to uncomment the following two cells to install the requirements and log in to huggingface with an access token.
from base64 import b64encode
import numpy
import torch
from diffusers import AutoencoderKL, LMSDiscreteScheduler, UNet2DConditionModel
from huggingface_hub import notebook_login
# For video display:
from IPython.display import HTML
from matplotlib import pyplot as plt
from pathlib import Path
from PIL import Image
from torch import autocast
from torchvision import transforms as tfms
from tqdm.auto import tqdm
from transformers import CLIPTextModel, CLIPTokenizer, logging
import os
1)
torch.manual_seed(if not (Path.home()/'.cache/huggingface'/'token').exists(): notebook_login()
# Supress some unnecessary warnings when loading the CLIPTextModel
logging.set_verbosity_error()
# Set device
= "cpu" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"
torch_device if "mps" == torch_device: os.environ['PYTORCH_ENABLE_MPS_FALLBACK'] = "1"
Loading the models
This code (and that in the next section) comes from the Huggingface example notebook.
This will download and set up the relevant models and components we’ll be using. Let’s just run this for now and move on to the next section to check that it all works before diving deeper.
If you’ve loaded a pipeline, you can also access these components using pipe.unet
, pipe.vae
and so on.
In this notebook we aren’t doing any memory-saving tricks - if you find yourself running out of GPU RAM, look at the pipeline code for inspiration with things like attention slicing, switching to half precision (fp16), keeping the VAE on the CPU and other modifications.
# Load the autoencoder model which will be used to decode the latents into image space.
= AutoencoderKL.from_pretrained("CompVis/stable-diffusion-v1-4", subfolder="vae")
vae
# Load the tokenizer and text encoder to tokenize and encode the text.
= CLIPTokenizer.from_pretrained("openai/clip-vit-large-patch14")
tokenizer = CLIPTextModel.from_pretrained("openai/clip-vit-large-patch14")
text_encoder
# The UNet model for generating the latents.
= UNet2DConditionModel.from_pretrained("CompVis/stable-diffusion-v1-4", subfolder="unet") unet
# The noise scheduler
= LMSDiscreteScheduler(beta_start=0.00085, beta_end=0.012, beta_schedule="scaled_linear", num_train_timesteps=1000) scheduler
# To the GPU we go!
= vae.to(torch_device)
vae = text_encoder.to(torch_device)
text_encoder = unet.to(torch_device); unet
A diffusion loop
If all you want is to make a picture with some text, you could ignore this notebook and use one of the existing tools (such as DreamStudio) or use the simplified pipeline from huggingface, as documented here.
What we want to do in this notebook is dig a little deeper into how this works, so we’ll start by checking that the example code runs. Again, this is adapted from the HF notebook and looks very similar to what you’ll find if you inspect the __call__()
method of the stable diffusion pipeline.
# Prep Scheduler
def set_timesteps(scheduler, num_inference_steps):
scheduler.set_timesteps(num_inference_steps)= scheduler.timesteps.to(torch.float32) # minor fix to ensure MPS compatibility, fixed in diffusers PR 3925 scheduler.timesteps
# Some settings
= ["A watercolor painting of an otter"]
prompt = 512 # default height of Stable Diffusion
height = 512 # default width of Stable Diffusion
width = 30 # Number of denoising steps
num_inference_steps = 7.5 # Scale for classifier-free guidance
guidance_scale = torch.manual_seed(32) # Seed generator to create the inital latent noise
generator = 1
batch_size
# Prep text
= tokenizer(prompt, padding="max_length", max_length=tokenizer.model_max_length, truncation=True, return_tensors="pt")
text_input with torch.no_grad():
= text_encoder(text_input.input_ids.to(torch_device))[0]
text_embeddings = text_input.input_ids.shape[-1]
max_length = tokenizer(
uncond_input ""] * batch_size, padding="max_length", max_length=max_length, return_tensors="pt"
[
)with torch.no_grad():
= text_encoder(uncond_input.input_ids.to(torch_device))[0]
uncond_embeddings = torch.cat([uncond_embeddings, text_embeddings]) text_embeddings
set_timesteps(scheduler,num_inference_steps)
# Prep latents
= torch.randn(
latents // 8, width // 8),
(batch_size, unet.in_channels, height =generator,
generator
)= latents.to(torch_device)
latents = latents * scheduler.init_noise_sigma # Scaling (previous versions did latents = latents * self.scheduler.sigmas[0]
latents
# Loop
with autocast("cpu"): # will fallback to CPU if no CUDA; no autocast for MPS
for i, t in tqdm(enumerate(scheduler.timesteps), total=len(scheduler.timesteps)):
# expand the latents if we are doing classifier-free guidance to avoid doing two forward passes.
= torch.cat([latents] * 2)
latent_model_input = scheduler.sigmas[i]
sigma # Scale the latents (preconditioning):
# latent_model_input = latent_model_input / ((sigma**2 + 1) ** 0.5) # Diffusers 0.3 and below
= scheduler.scale_model_input(latent_model_input, t)
latent_model_input
# predict the noise residual
with torch.no_grad():
= unet(latent_model_input, t, encoder_hidden_states=text_embeddings).sample
noise_pred
# perform guidance
= noise_pred.chunk(2)
noise_pred_uncond, noise_pred_text = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
noise_pred
# compute the previous noisy sample x_t -> x_t-1
# latents = scheduler.step(noise_pred, i, latents)["prev_sample"] # Diffusers 0.3 and below
= scheduler.step(noise_pred, t, latents).prev_sample
latents
# scale and decode the image latents with vae
= 1 / 0.18215 * latents latents
with torch.no_grad():
= vae.decode(latents).sample
image
# Display
= (image / 2 + 0.5).clamp(0, 1)
image = image.detach().cpu().permute(0, 2, 3, 1).numpy()
image = (image * 255).round().astype("uint8")
images = [Image.fromarray(image) for image in images]
pil_images 0] pil_images[
It’s working, but that’s quite a bit of code! Let’s look at the components one by one.
The Autoencoder (AE)
The AE can ‘encode’ an image into some sort of latent representation, and decode this back into an image. I’ve wrapped the code for this into a couple of functions here so we can see what this looks like in action:
def pil_to_latent(input_im):
# Single image -> single latent in a batch (so size 1, 4, 64, 64)
with torch.no_grad():
= vae.encode(tfms.ToTensor()(input_im).unsqueeze(0).to(torch_device)*2-1) # Note scaling
latent return 0.18215 * latent.latent_dist.sample()
def latents_to_pil(latents):
# bath of latents -> list of images
= (1 / 0.18215) * latents
latents with torch.no_grad():
= vae.decode(latents).sample
image = (image / 2 + 0.5).clamp(0, 1)
image = image.detach().cpu().permute(0, 2, 3, 1).numpy()
image = (image * 255).round().astype("uint8")
images = [Image.fromarray(image) for image in images]
pil_images return pil_images
We’ll use a pic from the web here, but you can load your own instead by uploading it and editing the filename in the next cell.
# Download a demo Image
!curl --output macaw.jpg 'https://lafeber.com/pet-birds/wp-content/uploads/2018/06/Scarlet-Macaw-2.jpg'
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 62145 100 62145 0 0 57588 0 0:00:01 0:00:01 --:--:-- 57648
# Load the image with PIL
= Image.open('macaw.jpg').resize((512, 512))
input_image input_image
Encoding this into the latent space of the AE with the function defined above looks like this:
# Encode to the latent space
= pil_to_latent(input_image)
encoded encoded.shape
torch.Size([1, 4, 64, 64])
# Let's visualize the four channels of this latent representation:
= plt.subplots(1, 4, figsize=(16, 4))
fig, axs for c in range(4):
0][c].cpu(), cmap='Greys') axs[c].imshow(encoded[
This 4x64x64 tensor captures lots of information about the image, hopefully enough that when we feed it through the decoder we get back something very close to our input image:
# Decode this latent representation back into an image
= latents_to_pil(encoded)[0]
decoded decoded
You’ll see some small differences if you squint! Forcus on the eye if you can’t see anything obvious. This is pretty impressive - that 4x64x64 latent seems to hold a lot more information that a 64px image…
This autoencoder has been trained to squish down an image to a smaller representation and then re-create the image back from this compressed version again.
In this particular case the compression factor is 48, we start with a 3x512x512(chxhtxwd) image and it get compressed to a latent vector 4x64x64. Each 3x8x8 pixel volume in the input image gets compressed down to just 4 numbers(4x1x1). You can find AEs with a higher compression ratio (eg f16 like some popular VQGAN models) but at some point they begin to introduce artifacts that we don’t want.
Why do we even use an autoencoder? We can do diffusion in pixel space - where the model gets all the image data as inputs and produces an output prediction of the same shape. But this means processing a LOT of data, and make high-resolution generation very computationally expensive. Some solutions to this involve doing diffusion at low resolution (64px for eg) and then training a separate model to upscale repeatedly (as with D2/Imagen). But latent diffusion instead does the diffusion process in this ‘latent space’, using the compressed representations from our AE rather than raw images. These representations are information rich, and can be small enough to handle manageably on consumer hardware. Once we’ve generated a new ‘image’ as a latent representation, the autoencoder can take those final latent outputs and turn them into actual pixels.
The Scheduler
Now we need to talk about adding noise…
During training, we add some noise to an image an then have the model try to predict the noise. If we always added a ton of noise, the model might not have much to work with. If we only add a tiny amount, the model won’t be able to do much with the random starting points we use for sampling. So during training the amount is varied, according to some distribution.
During sampling, we want to ‘denoise’ over a number of steps. How many steps and how much noise we should aim for at each step are going to affect the final result.
The scheduler is in charge of handling all of these details. For example: scheduler = LMSDiscreteScheduler(beta_start=0.00085, beta_end=0.012, beta_schedule="scaled_linear", num_train_timesteps=1000)
sets up a scheduler that matches the one used to train this model. When we want to sample over a smaller number of steps, we set this up with scheduler.set_timesteps
:
# Setting the number of sampling steps:
15) set_timesteps(scheduler,
You can see how our new set of steps corresponds to those used in training:
# See these in terms of the original 1000 steps used for training:
print(scheduler.timesteps)
tensor([999.0000, 927.6429, 856.2857, 784.9286, 713.5714, 642.2143, 570.8571,
499.5000, 428.1429, 356.7857, 285.4286, 214.0714, 142.7143, 71.3571,
0.0000])
And how much noise is present at each:
# Look at the equivalent noise levels:
print(scheduler.sigmas)
tensor([14.6146, 9.6826, 6.6780, 4.7746, 3.5221, 2.6666, 2.0606, 1.6156,
1.2768, 1.0097, 0.7913, 0.6056, 0.4397, 0.2780, 0.0292, 0.0000])
During sampling, we’ll start at a high noise level (in fact, our input will be pure noise) and gradually ‘denoise’ down to an image, according to this schedule.
# Plotting this noise schedule:
plt.plot(scheduler.sigmas)'Noise Schedule')
plt.title('Sampling step')
plt.xlabel('sigma')
plt.ylabel( plt.show()
# TODO maybe show timestep as well
This ‘sigma’ is the amount of noise added to the latent representation. Let’s visualize what this looks like by adding a bit of noise to our encoded image and then decoding this noised version:
= torch.randn_like(encoded) # Random noise
noise = 10 # Equivalent to step 10 out of 15 in the schedule above
sampling_step # encoded_and_noised = scheduler.add_noise(encoded, noise, timestep) # Diffusers 0.3 and below
= scheduler.add_noise(encoded, noise, timesteps=torch.tensor([scheduler.timesteps[sampling_step]]))
encoded_and_noised float())[0] # Display latents_to_pil(encoded_and_noised.
What does this look like at different timesteps? Experiment and see for yourself!
If you uncomment the cell below you’ll see that in this case the scheduler.add_noise
function literally just adds noise scaled by sigma: noisy_samples = original_samples + noise * sigmas
# ??scheduler.add_noise
Other diffusion models may be trained with different noising and scheduling approaches, some of which keep the variance fairly constant across noise levels (‘variance preserving’) with different scaling and mixing tricks instead of having noisy latents with higher and higher variance as more noise is added (‘variance exploding’).
If we want to start from random noise instead of a noised image, we need to scale it by the largest sigma value used during training, ~14 in this case. And before these noisy latents are fed to the model they are scaled again in the so-called pre-conditioning step: latent_model_input = latent_model_input / ((sigma**2 + 1) ** 0.5)
(now handled by latent_model_input = scheduler.scale_model_input(latent_model_input, t)
).
Again, this scaling/pre-conditioning differs between papers and implementations, so keep an eye out for this if you work with a different type of diffusion model.
Loop starting from noised version of input (AKA image2image)
Let’s see what happens when we use our image as a starting point, adding some noise and then doing the final few denoising steps in the loop with a new prompt.
We’ll use a similar loop to the first demo, but we’ll skip the first start_step
steps.
To noise our image we’ll use code like that shown above, using the scheduler to noise it to a level equivalent to step 10 (start_step
).
# Settings (same as before except for the new prompt)
= ["A colorful dancer, nat geo photo"]
prompt = 512 # default height of Stable Diffusion
height = 512 # default width of Stable Diffusion
width = 50 # Number of denoising steps
num_inference_steps = 8 # Scale for classifier-free guidance
guidance_scale = torch.manual_seed(32) # Seed generator to create the inital latent noise
generator = 1
batch_size
# Prep text (same as before)
= tokenizer(prompt, padding="max_length", max_length=tokenizer.model_max_length, truncation=True, return_tensors="pt")
text_input with torch.no_grad():
= text_encoder(text_input.input_ids.to(torch_device))[0]
text_embeddings = text_input.input_ids.shape[-1]
max_length = tokenizer(
uncond_input ""] * batch_size, padding="max_length", max_length=max_length, return_tensors="pt"
[
)with torch.no_grad():
= text_encoder(uncond_input.input_ids.to(torch_device))[0]
uncond_embeddings = torch.cat([uncond_embeddings, text_embeddings])
text_embeddings
# Prep Scheduler (setting the number of inference steps)
set_timesteps(scheduler, num_inference_steps)
# Prep latents (noising appropriately for start_step)
= 10
start_step = scheduler.sigmas[start_step]
start_sigma = torch.randn_like(encoded)
noise = scheduler.add_noise(encoded, noise, timesteps=torch.tensor([scheduler.timesteps[start_step]]))
latents = latents.to(torch_device).float()
latents
# Loop
for i, t in tqdm(enumerate(scheduler.timesteps), total=len(scheduler.timesteps)):
if i >= start_step: # << This is the only modification to the loop we do
# expand the latents if we are doing classifier-free guidance to avoid doing two forward passes.
= torch.cat([latents] * 2)
latent_model_input = scheduler.sigmas[i]
sigma = scheduler.scale_model_input(latent_model_input, t)
latent_model_input
# predict the noise residual
with torch.no_grad():
= unet(latent_model_input, t, encoder_hidden_states=text_embeddings)["sample"]
noise_pred
# perform guidance
= noise_pred.chunk(2)
noise_pred_uncond, noise_pred_text = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
noise_pred
# compute the previous noisy sample x_t -> x_t-1
= scheduler.step(noise_pred, t, latents).prev_sample
latents
0] latents_to_pil(latents)[
You can see that some colours and structure from the image are kept, but we now have a new picture! The more noise you add and the more steps you do, the further away it gets from the input image.
This is how the popular img2img pipeline works. Again, if this is your end goal there are tools to make this easy!
But you can see that under the hood this is the same as the generation loop just skipping the first few steps and starting from a noised image rather than pure noise.
Explore changing how many steps are skipped and see how this affects the amount the image changes from the input.
Exploring the text -> embedding pipeline
We use a text encoder model to turn our text into a set of ‘embeddings’ which are fed to the diffusion model as conditioning. Let’s follow a piece of text through this process and see how it works.
# Our text prompt
= 'A picture of a puppy' prompt
We begin with tokenization:
# Turn the text into a sequnce of tokens:
= tokenizer(prompt, padding="max_length", max_length=tokenizer.model_max_length, truncation=True, return_tensors="pt")
text_input 'input_ids'][0] # View the tokens text_input[
tensor([49406, 320, 1674, 539, 320, 6829, 49407, 49407, 49407, 49407,
49407, 49407, 49407, 49407, 49407, 49407, 49407, 49407, 49407, 49407,
49407, 49407, 49407, 49407, 49407, 49407, 49407, 49407, 49407, 49407,
49407, 49407, 49407, 49407, 49407, 49407, 49407, 49407, 49407, 49407,
49407, 49407, 49407, 49407, 49407, 49407, 49407, 49407, 49407, 49407,
49407, 49407, 49407, 49407, 49407, 49407, 49407, 49407, 49407, 49407,
49407, 49407, 49407, 49407, 49407, 49407, 49407, 49407, 49407, 49407,
49407, 49407, 49407, 49407, 49407, 49407, 49407])
# See the individual tokens
for t in text_input['input_ids'][0][:8]: # We'll just look at the first 7 to save you from a wall of '<|endoftext|>'
print(t, tokenizer.decoder.get(int(t)))
tensor(49406) <|startoftext|>
tensor(320) a</w>
tensor(1674) picture</w>
tensor(539) of</w>
tensor(320) a</w>
tensor(6829) puppy</w>
tensor(49407) <|endoftext|>
tensor(49407) <|endoftext|>
# TODO call out that 6829 is puppy
We can jump straight to the final (output) embeddings like so:
# Grab the output embeddings
= text_encoder(text_input.input_ids.to(torch_device))[0]
output_embeddings print('Shape:', output_embeddings.shape)
output_embeddings
Shape: torch.Size([1, 77, 768])
tensor([[[-0.3884, 0.0229, -0.0522, ..., -0.4899, -0.3066, 0.0675],
[ 0.0290, -1.3258, 0.3085, ..., -0.5257, 0.9768, 0.6652],
[ 0.6942, 0.3538, 1.0991, ..., -1.5716, -1.2643, -0.0121],
...,
[-0.0221, -0.0053, -0.0089, ..., -0.7303, -1.3830, -0.3011],
[-0.0062, -0.0246, 0.0065, ..., -0.7326, -1.3745, -0.2953],
[-0.0536, 0.0269, 0.0444, ..., -0.7159, -1.3634, -0.3075]]],
device='cuda:0', grad_fn=<NativeLayerNormBackward0>)
We pass our tokens through the text_encoder and we magically get some numbers we can feed to the model.
How are these generated? The tokens are transformed into a set of input embeddings, which are then fed through the transformer model to get the final output embeddings.
To get these input embeddings, there are actually two steps - as revealed by inspecting text_encoder.text_model.embeddings
:
text_encoder.text_model.embeddings
CLIPTextEmbeddings(
(token_embedding): Embedding(49408, 768)
(position_embedding): Embedding(77, 768)
)
Token embeddings
The token is fed to the token_embedding
to transform it into a vector. The function name get_input_embeddings
here is misleading since these token embeddings need to be combined with the position embeddings before they are actually used as inputs to the model! Anyway, let’s look at just the token embedding part first
We can look at the embedding layer:
# Access the embedding layer
= text_encoder.text_model.embeddings.token_embedding
token_emb_layer # Vocab size 49408, emb_dim 768 token_emb_layer
Embedding(49408, 768)
And embed a token like so:
# Embed a token - in this case the one for 'puppy'
= token_emb_layer(torch.tensor(6829, device=torch_device))
embedding # 768-dim representation embedding.shape
torch.Size([768])
This single token has been mapped to a 768-dimensional vector - the token embedding.
We can do the same with all of the tokens in the prompt to get all the token embeddings:
= token_emb_layer(text_input.input_ids.to(torch_device))
token_embeddings print(token_embeddings.shape) # batch size 1, 77 tokens, 768 values for each
token_embeddings
torch.Size([1, 77, 768])
tensor([[[ 0.0011, 0.0032, 0.0003, ..., -0.0018, 0.0003, 0.0019],
[ 0.0013, -0.0011, -0.0126, ..., -0.0124, 0.0120, 0.0080],
[ 0.0235, -0.0118, 0.0110, ..., 0.0049, 0.0078, 0.0160],
...,
[ 0.0012, 0.0077, -0.0011, ..., -0.0015, 0.0009, 0.0052],
[ 0.0012, 0.0077, -0.0011, ..., -0.0015, 0.0009, 0.0052],
[ 0.0012, 0.0077, -0.0011, ..., -0.0015, 0.0009, 0.0052]]],
device='cuda:0', grad_fn=<EmbeddingBackward0>)
Positional Embeddings
Positional embeddings tell the model where in a sequence a token is. Much like the token embedding, this is a set of (optionally learnable) parameters. But now instead of dealing with ~50k tokens we just need one for each position (77 total):
= text_encoder.text_model.embeddings.position_embedding
pos_emb_layer pos_emb_layer
Embedding(77, 768)
We can get the positional embedding for each position:
= text_encoder.text_model.embeddings.position_ids[:, :77]
position_ids = pos_emb_layer(position_ids)
position_embeddings print(position_embeddings.shape)
position_embeddings
torch.Size([1, 77, 768])
tensor([[[ 0.0016, 0.0020, 0.0002, ..., -0.0013, 0.0008, 0.0015],
[ 0.0042, 0.0029, 0.0002, ..., 0.0010, 0.0015, -0.0012],
[ 0.0018, 0.0007, -0.0012, ..., -0.0029, -0.0009, 0.0026],
...,
[ 0.0216, 0.0055, -0.0101, ..., -0.0065, -0.0029, 0.0037],
[ 0.0188, 0.0073, -0.0077, ..., -0.0025, -0.0009, 0.0057],
[ 0.0330, 0.0281, 0.0289, ..., 0.0160, 0.0102, -0.0310]]],
device='cuda:0', grad_fn=<EmbeddingBackward0>)
Combining token and position embeddings
Time to combine the two. How do we do this? Just add them! Other approaches are possible but for this model this is how it is done.
Combining them in this way gives us the final input embeddings ready to feed through the transformer model:
# And combining them we get the final input embeddings
= token_embeddings + position_embeddings
input_embeddings print(input_embeddings.shape)
input_embeddings
torch.Size([1, 77, 768])
tensor([[[ 2.6770e-03, 5.2133e-03, 4.9323e-04, ..., -3.1321e-03,
1.0659e-03, 3.4316e-03],
[ 5.5371e-03, 1.7510e-03, -1.2381e-02, ..., -1.1410e-02,
1.3508e-02, 6.8378e-03],
[ 2.5356e-02, -1.1019e-02, 9.7663e-03, ..., 1.9460e-03,
6.8375e-03, 1.8573e-02],
...,
[ 2.2781e-02, 1.3262e-02, -1.1241e-02, ..., -8.0054e-03,
-2.0560e-03, 8.9366e-03],
[ 2.0026e-02, 1.5015e-02, -8.7638e-03, ..., -4.0313e-03,
1.8487e-05, 1.0885e-02],
[ 3.4206e-02, 3.5826e-02, 2.7768e-02, ..., 1.4465e-02,
1.1110e-02, -2.5745e-02]]], device='cuda:0', grad_fn=<AddBackward0>)
We can check that these are the same as the result we’d get from text_encoder.text_model.embeddings
:
# The following combines all the above steps (but doesn't let us fiddle with them!)
text_encoder.text_model.embeddings(text_input.input_ids.to(torch_device))
tensor([[[ 2.6770e-03, 5.2133e-03, 4.9323e-04, ..., -3.1321e-03,
1.0659e-03, 3.4316e-03],
[ 5.5371e-03, 1.7510e-03, -1.2381e-02, ..., -1.1410e-02,
1.3508e-02, 6.8378e-03],
[ 2.5356e-02, -1.1019e-02, 9.7663e-03, ..., 1.9460e-03,
6.8375e-03, 1.8573e-02],
...,
[ 2.2781e-02, 1.3262e-02, -1.1241e-02, ..., -8.0054e-03,
-2.0560e-03, 8.9366e-03],
[ 2.0026e-02, 1.5015e-02, -8.7638e-03, ..., -4.0313e-03,
1.8487e-05, 1.0885e-02],
[ 3.4206e-02, 3.5826e-02, 2.7768e-02, ..., 1.4465e-02,
1.1110e-02, -2.5745e-02]]], device='cuda:0', grad_fn=<AddBackward0>)
Feeding these through the transformer model
We want to mess with these input embeddings (specifically the token embeddings) before we send them through the rest of the model, but first we should check that we know how to do that. I read the code of the text_encoders forward
method, and based on that the code for the forward
method of the text_model that the text_encoder wraps. To inspect it yourself, type ??text_encoder.text_model.forward
and you’ll get the function info and source code - a useful debugging trick!
Anyway, based on that we can copy in the bits we need to get the so-called ‘last hidden state’ and thus generate our final embeddings:
def get_output_embeds(input_embeddings):
# CLIP's text model uses causal mask, so we prepare it here:
= input_embeddings.shape[:2]
bsz, seq_len = text_encoder.text_model._build_causal_attention_mask(bsz, seq_len, dtype=input_embeddings.dtype)
causal_attention_mask
# Getting the output embeddings involves calling the model with passing output_hidden_states=True
# so that it doesn't just return the pooled final predictions:
= text_encoder.text_model.encoder(
encoder_outputs =input_embeddings,
inputs_embeds=None, # We aren't using an attention mask so that can be None
attention_mask=causal_attention_mask.to(torch_device),
causal_attention_mask=None,
output_attentions=True, # We want the output embs not the final output
output_hidden_states=None,
return_dict
)
# We're interested in the output hidden state only
= encoder_outputs[0]
output
# There is a final layer norm we need to pass these through
= text_encoder.text_model.final_layer_norm(output)
output
# And now they're ready!
return output
= get_output_embeds(input_embeddings) # Feed through the model with our new function
out_embs_test print(out_embs_test.shape) # Check the output shape
# Inspect the output out_embs_test
torch.Size([1, 77, 768])
tensor([[[-0.3884, 0.0229, -0.0522, ..., -0.4899, -0.3066, 0.0675],
[ 0.0290, -1.3258, 0.3085, ..., -0.5257, 0.9768, 0.6652],
[ 0.6942, 0.3538, 1.0991, ..., -1.5716, -1.2643, -0.0121],
...,
[-0.0221, -0.0053, -0.0089, ..., -0.7303, -1.3830, -0.3011],
[-0.0062, -0.0246, 0.0065, ..., -0.7326, -1.3745, -0.2953],
[-0.0536, 0.0269, 0.0444, ..., -0.7159, -1.3634, -0.3075]]],
device='cuda:0', grad_fn=<NativeLayerNormBackward0>)
Note that these match the output_embeddings
we saw near the start - we’ve figured out how to split up that one step (“get the text embeddings”) into multiple sub-steps ready for us to modify.
Now that we have this process in place, we can replace the input embedding of a token with a new one of our choice - which in our final use-case will be something we learn. To demonstrate the concept though, let’s replace the input embedding for ‘puppy’ in the prompt we’ve been playing with with the embedding for token 2368, get a new set of output embeddings based on this, and use these to generate an image to see what we get:
= 'A picture of a puppy'
prompt
# Tokenize
= tokenizer(prompt, padding="max_length", max_length=tokenizer.model_max_length, truncation=True, return_tensors="pt")
text_input = text_input.input_ids.to(torch_device)
input_ids
# Get token embeddings
= token_emb_layer(input_ids)
token_embeddings
# The new embedding. In this case just the input embedding of token 2368...
= text_encoder.get_input_embeddings()(torch.tensor(2368, device=torch_device))
replacement_token_embedding
# Insert this into the token embeddings (
0, torch.where(input_ids[0]==6829)] = replacement_token_embedding.to(torch_device)
token_embeddings[
# Combine with pos embs
= token_embeddings + position_embeddings
input_embeddings
# Feed through to get final output embs
= get_output_embeds(input_embeddings)
modified_output_embeddings
print(modified_output_embeddings.shape)
modified_output_embeddings
torch.Size([1, 77, 768])
tensor([[[-0.3884, 0.0229, -0.0522, ..., -0.4899, -0.3066, 0.0675],
[ 0.0290, -1.3258, 0.3085, ..., -0.5257, 0.9768, 0.6652],
[ 0.6942, 0.3538, 1.0991, ..., -1.5716, -1.2643, -0.0121],
...,
[-0.6034, -0.5322, 0.0629, ..., -0.3964, 0.0877, -0.9558],
[-0.5936, -0.5407, 0.0731, ..., -0.3876, 0.0906, -0.9436],
[-0.6393, -0.4703, 0.1103, ..., -0.3904, 0.1351, -0.9726]]],
device='cuda:0', grad_fn=<NativeLayerNormBackward0>)
The first few are the same, the last aren’t. Everything at and after the position of the token we’re replacing will be affected.
If all went well, we should see something other than a puppy when we use these to generate an image. And sure enough, we do!
#Generating an image with these modified embeddings
def generate_with_embs(text_embeddings):
= 512 # default height of Stable Diffusion
height = 512 # default width of Stable Diffusion
width = 30 # Number of denoising steps
num_inference_steps = 7.5 # Scale for classifier-free guidance
guidance_scale = torch.manual_seed(32) # Seed generator to create the inital latent noise
generator = 1
batch_size
= text_input.input_ids.shape[-1]
max_length = tokenizer(
uncond_input ""] * batch_size, padding="max_length", max_length=max_length, return_tensors="pt"
[
)with torch.no_grad():
= text_encoder(uncond_input.input_ids.to(torch_device))[0]
uncond_embeddings = torch.cat([uncond_embeddings, text_embeddings])
text_embeddings
# Prep Scheduler
set_timesteps(scheduler, num_inference_steps)
# Prep latents
= torch.randn(
latents // 8, width // 8),
(batch_size, unet.in_channels, height =generator,
generator
)= latents.to(torch_device)
latents = latents * scheduler.init_noise_sigma
latents
# Loop
for i, t in tqdm(enumerate(scheduler.timesteps), total=len(scheduler.timesteps)):
# expand the latents if we are doing classifier-free guidance to avoid doing two forward passes.
= torch.cat([latents] * 2)
latent_model_input = scheduler.sigmas[i]
sigma = scheduler.scale_model_input(latent_model_input, t)
latent_model_input
# predict the noise residual
with torch.no_grad():
= unet(latent_model_input, t, encoder_hidden_states=text_embeddings)["sample"]
noise_pred
# perform guidance
= noise_pred.chunk(2)
noise_pred_uncond, noise_pred_text = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
noise_pred
# compute the previous noisy sample x_t -> x_t-1
= scheduler.step(noise_pred, t, latents).prev_sample
latents
return latents_to_pil(latents)[0]
generate_with_embs(modified_output_embeddings)
/tmp/ipykernel_8407/342776162.py:24: FutureWarning: Accessing config attribute `in_channels` directly via 'UNet2DConditionModel' object attribute is deprecated. Please access 'in_channels' over 'UNet2DConditionModel's config object instead, e.g. 'unet.config.in_channels'.
(batch_size, unet.in_channels, height // 8, width // 8),
Suprise! Now you know what token 2368 means ;)
What can we do with this? Why did we go to all of this trouble? Well, we’ll see a more compelling use-case shortly but the tl;dr is that once we can access and modify the token embeddings we can do tricks like replacing them with something else. In the example we just did, that was just another token embedding from the model’s vocabulary, equivalent to just editing the prompt. But we can also mix tokens - for example, here’s a half-puppy-half-skunk:
# In case you're wondering how to get the token for a word, or the embedding for a token:
= 'skunk'
prompt print('tokenizer(prompt):', tokenizer(prompt))
print('token_emb_layer([token_id]) shape:', token_emb_layer(torch.tensor([8797], device=torch_device)).shape)
tokenizer(prompt): {'input_ids': [49406, 42194, 49407], 'attention_mask': [1, 1, 1]}
token_emb_layer([token_id]) shape: torch.Size([1, 768])
= 'A picture of a puppy'
prompt
# Tokenize
= tokenizer(prompt, padding="max_length", max_length=tokenizer.model_max_length, truncation=True, return_tensors="pt")
text_input = text_input.input_ids.to(torch_device)
input_ids
# Get token embeddings
= token_emb_layer(input_ids)
token_embeddings
# The new embedding. Which is now a mixture of the token embeddings for 'puppy' and 'skunk'
= token_emb_layer(torch.tensor(6829, device=torch_device))
puppy_token_embedding = token_emb_layer(torch.tensor(42194, device=torch_device))
skunk_token_embedding = 0.5*puppy_token_embedding + 0.5*skunk_token_embedding
replacement_token_embedding
# Insert this into the token embeddings (
0, torch.where(input_ids[0]==6829)] = replacement_token_embedding.to(torch_device)
token_embeddings[
# Combine with pos embs
= token_embeddings + position_embeddings
input_embeddings
# Feed through to get final output embs
= get_output_embeds(input_embeddings)
modified_output_embeddings
# Generate an image with these
generate_with_embs(modified_output_embeddings)
/tmp/ipykernel_8407/342776162.py:24: FutureWarning: Accessing config attribute `in_channels` directly via 'UNet2DConditionModel' object attribute is deprecated. Please access 'in_channels' over 'UNet2DConditionModel's config object instead, e.g. 'unet.config.in_channels'.
(batch_size, unet.in_channels, height // 8, width // 8),
Textual Inversion
OK, so we can slip in a modified token embedding, and use this to generate an image. We used the token embedding for ‘cat’ in the above example, but what if instead could ‘learn’ a new token embedding for a specific concept? This is the idea behind ‘Textual Inversion’, in which a few example images are used to create a new token embedding:
Diagram from the textual inversion blog post - note it doesn’t show the positional embeddings step for simplicity
We won’t cover how this training works, but we can try loading one of these new ‘concepts’ from the community-created SD concepts library and see how it fits in with our example above. I’ll use https://huggingface.co/sd-concepts-library/birb-style since it was the first one I made :) Download the learned_embeds.bin file from there and upload the file to wherever this notebook is before running this next cell:
= torch.load('learned_embeds.bin')
birb_embed '<birb-style>'].shape birb_embed.keys(), birb_embed[
(dict_keys(['<birb-style>']), torch.Size([768]))
We get a dictionary with a key (the special placeholder I used,
= 'A mouse in the style of puppy'
prompt
# Tokenize
= tokenizer(prompt, padding="max_length", max_length=tokenizer.model_max_length, truncation=True, return_tensors="pt")
text_input = text_input.input_ids.to(torch_device)
input_ids
# Get token embeddings
= token_emb_layer(input_ids)
token_embeddings
# The new embedding - our special birb word
= birb_embed['<birb-style>'].to(torch_device)
replacement_token_embedding
# Insert this into the token embeddings
0, torch.where(input_ids[0]==6829)] = replacement_token_embedding.to(torch_device)
token_embeddings[
# Combine with pos embs
= token_embeddings + position_embeddings
input_embeddings
# Feed through to get final output embs
= get_output_embeds(input_embeddings)
modified_output_embeddings
# And generate an image with this:
generate_with_embs(modified_output_embeddings)
/tmp/ipykernel_8407/342776162.py:24: FutureWarning: Accessing config attribute `in_channels` directly via 'UNet2DConditionModel' object attribute is deprecated. Please access 'in_channels' over 'UNet2DConditionModel's config object instead, e.g. 'unet.config.in_channels'.
(batch_size, unet.in_channels, height // 8, width // 8),
The token for ‘puppy’ was replaced with one that captures a particular style of painting, but it could just as easily represent a specific object or class of objects.
Again, there is a nice inference notebook from hf to make it easy to use the different concepts, that properly handles using the names in prompts (“A <cat-toy> in the style of <birb-style>”) without worrying about all this manual stuff. The goal of this notebook is to pull back the curtain a bit so you know what is going on behind the scenes :)
Messing with Embeddings
Besides just replacing the token embedding of a single word, there are various other tricks we can try. For example, what if we create a ‘chimera’ by averaging the embeddings of two different prompts?
# Embed two prompts
= tokenizer(["A mouse"], padding="max_length", max_length=tokenizer.model_max_length, truncation=True, return_tensors="pt")
text_input1 = tokenizer(["A leopard"], padding="max_length", max_length=tokenizer.model_max_length, truncation=True, return_tensors="pt")
text_input2 with torch.no_grad():
= text_encoder(text_input1.input_ids.to(torch_device))[0]
text_embeddings1 = text_encoder(text_input2.input_ids.to(torch_device))[0]
text_embeddings2
# Mix them together
= 0.35
mix_factor = (text_embeddings1*mix_factor + \
mixed_embeddings *(1-mix_factor))
text_embeddings2
# Generate!
generate_with_embs(mixed_embeddings)
/tmp/ipykernel_8407/342776162.py:24: FutureWarning: Accessing config attribute `in_channels` directly via 'UNet2DConditionModel' object attribute is deprecated. Please access 'in_channels' over 'UNet2DConditionModel's config object instead, e.g. 'unet.config.in_channels'.
(batch_size, unet.in_channels, height // 8, width // 8),
The UNET and CFG
Now it’s time we looked at the actual diffusion model. This is typically a Unet that takes in the noisy latents (x) and predicts the noise. We use a conditional model that also takes in the timestep (t) and our text embedding (aka encoder_hidden_states) as conditioning. Feeding all of these into the model looks like this: noise_pred = unet(latents, t, encoder_hidden_states=text_embeddings)["sample"]
We can try it out and see what the output looks like:
# Prep Scheduler
set_timesteps(scheduler, num_inference_steps)
# What is our timestep
= scheduler.timesteps[0]
t = scheduler.sigmas[0]
sigma
# A noisy latent
= torch.randn(
latents // 8, width // 8),
(batch_size, unet.in_channels, height =generator,
generator
)= latents.to(torch_device)
latents = latents * scheduler.init_noise_sigma
latents
# Text embedding
= tokenizer(['A macaw'], padding="max_length", max_length=tokenizer.model_max_length, truncation=True, return_tensors="pt")
text_input with torch.no_grad():
= text_encoder(text_input.input_ids.to(torch_device))[0]
text_embeddings
# Run this through the unet to predict the noise residual
with torch.no_grad():
= unet(latents, t, encoder_hidden_states=text_embeddings)["sample"]
noise_pred
# We get preds in the same shape as the input latents.shape, noise_pred.shape
/tmp/ipykernel_8407/440475445.py:10: FutureWarning: Accessing config attribute `in_channels` directly via 'UNet2DConditionModel' object attribute is deprecated. Please access 'in_channels' over 'UNet2DConditionModel's config object instead, e.g. 'unet.config.in_channels'.
(batch_size, unet.in_channels, height // 8, width // 8),
(torch.Size([1, 4, 64, 64]), torch.Size([1, 4, 64, 64]))
Given a set of noisy latents, the model predicts the noise component. We can remove this noise from the noisy latents to see what the output image looks like (latents_x0 = latents - sigma * noise_pred
). And we can add most of the noise back to this predicted output to get the (slightly less noisy hopefully) input for the next diffusion step. To visualize this let’s generate another image, saving both the predicted output (x0) and the next step (xt-1) after every step:
= 'Oil painting of an otter in a top hat'
prompt = 512
height = 512
width = 50
num_inference_steps = 8
guidance_scale = torch.manual_seed(32)
generator = 1
batch_size
# Make a folder to store results
!rm -rf steps/
!mkdir -p steps/
# Prep text
= tokenizer([prompt], padding="max_length", max_length=tokenizer.model_max_length, truncation=True, return_tensors="pt")
text_input with torch.no_grad():
= text_encoder(text_input.input_ids.to(torch_device))[0]
text_embeddings = text_input.input_ids.shape[-1]
max_length = tokenizer(
uncond_input ""] * batch_size, padding="max_length", max_length=max_length, return_tensors="pt"
[
)with torch.no_grad():
= text_encoder(uncond_input.input_ids.to(torch_device))[0]
uncond_embeddings = torch.cat([uncond_embeddings, text_embeddings])
text_embeddings
# Prep Scheduler
set_timesteps(scheduler, num_inference_steps)
# Prep latents
= torch.randn(
latents // 8, width // 8),
(batch_size, unet.in_channels, height =generator,
generator
)= latents.to(torch_device)
latents = latents * scheduler.init_noise_sigma
latents
# Loop
for i, t in tqdm(enumerate(scheduler.timesteps), total=len(scheduler.timesteps)):
# expand the latents if we are doing classifier-free guidance to avoid doing two forward passes.
= torch.cat([latents] * 2)
latent_model_input = scheduler.sigmas[i]
sigma = scheduler.scale_model_input(latent_model_input, t)
latent_model_input
# predict the noise residual
with torch.no_grad():
= unet(latent_model_input, t, encoder_hidden_states=text_embeddings)["sample"]
noise_pred
# perform guidance
= noise_pred.chunk(2)
noise_pred_uncond, noise_pred_text = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
noise_pred
# Get the predicted x0:
# latents_x0 = latents - sigma * noise_pred # Calculating ourselves
= scheduler.step(noise_pred, t, latents).pred_original_sample # Using the scheduler (Diffusers 0.4 and above)
latents_x0
# compute the previous noisy sample x_t -> x_t-1
= scheduler.step(noise_pred, t, latents).prev_sample
latents
# To PIL Images
= latents_to_pil(latents_x0)[0]
im_t0 = latents_to_pil(latents)[0]
im_next
# Combine the two images and save for later viewing
= Image.new('RGB', (1024, 512))
im 0, 0))
im.paste(im_next, (512, 0))
im.paste(im_t0, (f'steps/{i:04}.jpeg') im.save(
/tmp/ipykernel_8407/2488592417.py:30: FutureWarning: Accessing config attribute `in_channels` directly via 'UNet2DConditionModel' object attribute is deprecated. Please access 'in_channels' over 'UNet2DConditionModel's config object instead, e.g. 'unet.config.in_channels'.
(batch_size, unet.in_channels, height // 8, width // 8),
# Make and show the progress video (change width to 1024 for full res)
!ffmpeg -v 1 -y -f image2 -framerate 12 -i steps/%04d.jpeg -c:v libx264 -preset slow -qp 18 -pix_fmt yuv420p out.mp4
= open('out.mp4','rb').read()
mp4 = "data:video/mp4;base64," + b64encode(mp4).decode()
data_url """
HTML(<video width=600 controls>
<source src="%s" type="video/mp4">
</video>
""" % data_url)
The version on the right shows the predicted ‘final output’ (x0) at each step, and this is what is usually used for progress videos etc. The version on the left is the ‘next step’. I found it interesteing to compare the two - watching the progress videos only you’d think drastic changes are happening expecially at early stages, but since the changes made per-step are relatively small the actual process is much more gradual.
Classifier Free Guidance
By default, the model doesn’t often do what we ask. If we want it to follow the prompt better, we use a hack called CFG. There’s a good explanation in this video (AI coffee break GLIDE).
In the code, this comes down to us doing:
noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
This works suprisingly well :) Explore changing the guidance_scale in the code above and see how this affects the results. How high can you push it before the results get worse?
Sampling
There is still some complexity hidden from us inside latents = scheduler.step(noise_pred, i, latents)["prev_sample"]
. How exactly does the sampler go from the current noisy latents to a slightly less noisy version? Why don’t we just use the model in a single step? Are there other ways to view this?
The model tries to predict the noise in an image. For low noise values, we assume it does a pretty good job. For higher noise levels, it has a hard task! So instead of producing a perfect image, the results tend to look like a blurry mess - see the start of the video above for a visual! So, samplers use the model predictions to move a small amount towards the model prediction (removing some of the noise) and then get another prediction based on this marginally-less-rubbish input, and hope that this iteratively improves the result.
Different samplers do this in different ways. You can try to inspect the code for the default LMS sampler with:
# ??scheduler.step
Time to draw some diagrams! (Whiteboard/paper interlude)
Guidance
OK, final trick! How can we add some extra control to this generation process?
At each step, we’re going to use our model as before to predict the noise component of x. Then we’ll use this to produce a predicted output image, and apply some loss function to this image.
This function can be anything, but let’s demo with a super simple example. If we want images that have a lot of blue, we can craft a loss function that gives a high loss if pixels have a low blue component:
def blue_loss(images):
# How far are the blue channel values to 0.9:
= torch.abs(images[:,2] - 0.9).mean() # [:,2] -> all images in batch, only the blue channel
error return error
During each update step, we find the gradient of the loss with respect to the current noisy latents, and tweak them in the direction that reduces this loss as well as performing the normal update step:
= 'A campfire (oil on canvas)' #@param
prompt = 512 # default height of Stable Diffusion
height = 512 # default width of Stable Diffusion
width = 50 #@param # Number of denoising steps
num_inference_steps = 8 #@param # Scale for classifier-free guidance
guidance_scale = torch.manual_seed(32) # Seed generator to create the inital latent noise
generator = 1
batch_size = 200 #@param
blue_loss_scale
# Prep text
= tokenizer([prompt], padding="max_length", max_length=tokenizer.model_max_length, truncation=True, return_tensors="pt")
text_input with torch.no_grad():
= text_encoder(text_input.input_ids.to(torch_device))[0]
text_embeddings
# And the uncond. input as before:
= text_input.input_ids.shape[-1]
max_length = tokenizer(
uncond_input ""] * batch_size, padding="max_length", max_length=max_length, return_tensors="pt"
[
)with torch.no_grad():
= text_encoder(uncond_input.input_ids.to(torch_device))[0]
uncond_embeddings = torch.cat([uncond_embeddings, text_embeddings])
text_embeddings
# Prep Scheduler
set_timesteps(scheduler, num_inference_steps)
# Prep latents
= torch.randn(
latents // 8, width // 8),
(batch_size, unet.in_channels, height =generator,
generator
)= latents.to(torch_device)
latents = latents * scheduler.init_noise_sigma
latents
# Loop
for i, t in tqdm(enumerate(scheduler.timesteps), total=len(scheduler.timesteps)):
# expand the latents if we are doing classifier-free guidance to avoid doing two forward passes.
= torch.cat([latents] * 2)
latent_model_input = scheduler.sigmas[i]
sigma = scheduler.scale_model_input(latent_model_input, t)
latent_model_input
# predict the noise residual
with torch.no_grad():
= unet(latent_model_input, t, encoder_hidden_states=text_embeddings)["sample"]
noise_pred
# perform CFG
= noise_pred.chunk(2)
noise_pred_uncond, noise_pred_text = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
noise_pred
#### ADDITIONAL GUIDANCE ###
if i%5 == 0:
# Requires grad on the latents
= latents.detach().requires_grad_()
latents
# Get the predicted x0:
# latents_x0 = latents - sigma * noise_pred
= scheduler.step(noise_pred, t, latents).pred_original_sample
latents_x0
# Decode to image space
= vae.decode((1 / 0.18215) * latents_x0).sample / 2 + 0.5 # range (0, 1)
denoised_images
# Calculate loss
= blue_loss(denoised_images) * blue_loss_scale
loss
# Occasionally print it out
if i%10==0:
print(i, 'loss:', loss.item())
# Get gradient
= torch.autograd.grad(loss, latents)[0]
cond_grad
# Modify the latents based on this gradient
= latents.detach() - cond_grad * sigma**2
latents
# Now step with scheduler
= scheduler.step(noise_pred, t, latents).prev_sample latents
0] latents_to_pil(latents)[
Tweak the scale (blue_loss_scale
) - at low values, the image is mostly red and orange thanks to the prompt. At higher values, it is mostly bluish! Too high and we get a plain blue image.
Since this is slow, you’ll notice that I only apply this loss once every 5 iterations - this was a suggestion from Jeremy and we left it in because for this demo it saves time and still works. For your own tests you may want to explore using a lower scale for the loss and applying it every iteration instead :)
NB: We should set latents requires_grad=True before we do the forward pass of the unet (removing with torch.no_grad()
) if we want mode accurate gradients. BUT this requires a lot of extra memory. You’ll see both approaches used depending on whose implementation you’re looking at.
Guiding with classifier models can give you images of a specific class. Guiding with a model like CLIP can help better match a text prompt. Guiding with a style loss can help add a particular style. Guiding with some sort of perceptual loss can force it towards the overall look af a target image. And so on.
Conclusions
Hopefully now you have a slightly better idea of what is happening when you make an image with one of these models, and how you can modify the process in creative ways. I hope you’re inspired to make something fun :)
This notebook was written by Jonathan Whitaker, adapted from ‘Grokking Stable Diffusion’ which was my early attempts to understand these components for myself. If you spot bugs or have questions, feel free to reach out to me @johnowhitaker :) Enjoy!